package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Resource
    private KafkaTemplate<String,String > kafkaTemplate;

    /**
     * 加载文章列表
     * @param dto
     * @param type 1 加载更多 2 加载最新
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, Short type) {
        // 判断页数
        Integer size = dto.getSize();
        if(size == null || size ==0){
            size = 10;
        }
        // 分页纸不超过50
        size = Math.min(size, MAX_PAGE_SIZE);
        // 检查参数--->type
        if(!type.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !type.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        // 检查tag
        if(StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 检查时间
        if(dto.getMaxBehotTime() == null)dto.setMaxBehotTime(new Date());
        if(dto.getMinBehotTime() == null)dto.setMinBehotTime(new Date());


        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, type);
        return apArticles!=null ? ResponseResult.okResult(apArticles): ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }


    /**
     * 新增文章
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult save(ArticleDto dto) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        if(dto.getId() == null){
            // 1,新增
            apArticle.setCreatedTime(new Date());
            apArticle.setPublishTime(new Date());
            int insert = apArticleMapper.insert(apArticle);
            // 因为使用雪花算法,所在不用等待主表新增成功就能拿到新增的文章id
            // 2,往配置表添加数据
            ApArticleConfig articleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(articleConfig);
            // 3,把文本内容添加到ap_article_content表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        }else{
            // 修改
            apArticleMapper.updateById(apArticle);
            // 修改ap_article_content
            ApArticleContent articleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()));
            if(articleContent != null){
                articleContent.setContent(dto.getContent());
                apArticleContentMapper.updateById(articleContent);
            }
        }
        // 生成静态文件
        buildArticleToMinIO(apArticle.getId().longValue());
        return ResponseResult.okResult(apArticle.getId()); // 返回id去修改WmNews状态
    }

    /**
     * 生成静态文件上传到minIO中
     * @param articleId
     */
    @Async
    public void buildArticleToMinIO(Long articleId) {
        try {
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(
                    Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleId)
            );

            if(apArticleContent != null && StringUtils.isNotBlank(apArticleContent.getContent())){
                // 文章通过freemarker生成静态文件
                StringWriter out = new StringWriter();
                Template template = configuration.getTemplate("article.ftl");
                Map map = new HashMap<>();
                map.put("content", JSONArray.parseArray(apArticleContent.getContent()));
                log.info("{}",out);
                // 把html文件上传到minio
                ByteArrayInputStream stream = new ByteArrayInputStream(out.toString().getBytes());
                String htmlFile = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", stream);

                //4.修改ap_article表中的static_url字段，保存是静态化文件保存在minio中的路径地址
                ApArticle aparticle = apArticleMapper.selectById(apArticleContent.getArticleId());
                if(aparticle!=null){
                    aparticle.setStaticUrl(htmlFile);
                    apArticleMapper.updateById(aparticle);
                }
//                // 修改文章地址字段
//                apArticleService.update(
//                        Wrappers.<ApArticle>lambdaUpdate().eq(ApArticle::getId,articleId)
//                        .set(ApArticle::getStaticUrl,htmlFile)
//                );
                // 发送kafka消息新增文章数据到es
                producKafka(aparticle, apArticleContent.getContent());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过kafka发送消息
     */
    private void producKafka(ApArticle apArticle,String content){
        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, searchArticleVo);
        searchArticleVo.setLayout(apArticle.getLayout().intValue());
        searchArticleVo.setContent(content);
        log.info("kafka发送消息开始");
        kafkaTemplate.send(WmNewsMessageConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));
        log.info("kafka发送消息结束");
    }

}
